<?php

namespace app\airobot\controller;

use app\airobot\CommonLogic;
use app\airobot\model\ConfigFileHistory;
use app\airobot\model\ConfigFileOnline;
use app\airobot\model\ConfigFileTmp;
use app\airobot\model\OriginConfigFileTmp;
use think\admin\Controller;
use think\facade\Db;
use ZipArchive;

/**
 * 超管系统-配置记录
 * Class ConfigFileRecord
 * @package app\airobot\controller
 */
class ConfigFileRecord extends Controller
{
    private $table = 'config_file_history';
    public $commonLogic;

    /**
     * 配置记录
     * @auth true
     */
    public function index()
    {
        $this->commonLogic = new CommonLogic();
        $this->title = '配置记录';
        $this->stime = $this->get['stime'] ?? '';
        $this->etime = $this->get['etime'] ?? '';

        $query = $this->_query($this->table);
        if (!empty($_GET['stime'])) {
            $query->where('created_at', '>=', $_GET['stime'] . ' 00:00:00');
        }
        if (!empty($_GET['etime'])) {
            $query->where('created_at', '<=', $_GET['etime'] . ' 23:59:59');
        }
        $query->order('id desc')->page();
    }

    protected function _index_page_filter(array &$data)
    {
        foreach ($data as &$vo) {
            $configFile = explode('|', $vo['config_file']);
            $fileNameArr = [];
            foreach ($configFile as $file) {
                // 文件名
                $fileArr = explode("/", $file);
                $fileArrItem = explode("-", $fileArr[count($fileArr) - 1]);
                $fileNameArr[] = $fileArrItem[count($fileArrItem) - 1];
            }
            $vo['config_file'] = $fileNameArr;
        }
    }

    public function download()
    {
        // 保存
        try {
            $id = $this->app->request->post('id');
            $configFile = Db::table('config_file_history')->where(['id' => $id])->find();
            $files = explode("|", $configFile['config_file']);
            $zip = new ZipArchive();
            $zipFilename = 'download-' . time() . '.zip';
            if ($zip->open($zipFilename, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
                foreach ($files as $file) {
                    // 文件名
                    $fileArr = explode("/", $file);
                    $fileNameArr = explode("-", $fileArr[count($fileArr) - 1]);
                    $fileName = $fileNameArr[count($fileNameArr) - 1];

                    // 检查文件是否存在
                    if (file_exists($file)) {
                        // 添加文件到 ZIP
                        $zip->addFile($file, $fileName);
                    } else {
                        echo "文件不存在: $file<br>";
                    }
                }
                $zip->close();
            } else {
                echo '无法创建 ZIP 文件。';
                exit;
            }

            // 设置适当的头部
            header('Content-Description: File Transfer');
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="' . basename($zipFilename) . '"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($zipFilename));

            // 清空输出缓冲区
            ob_clean();
            flush();

            // 输出 ZIP 文件
            readfile($zipFilename);

            // 删除 ZIP 文件（可选）
            unlink($zipFilename);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }
}